﻿using System;
using System.Xml.Serialization;
using System.Xml;

namespace Daystate.ConfigurationManager
{
    /// <summary>
    /// Configuration property.
    /// </summary>
    public class ConfigProperty : IXmlSerializable
    {
        /// <summary>
        /// Properties key.
        /// </summary>
        public string Key;

        /// <summary>
        /// Properties value.
        /// </summary>
        public object Value;


        /// <summary>
        /// Gets property value.
        /// </summary>
        /// <typeparam name="T">Property expected type.</typeparam>
        /// <returns>Property value.</returns>
        public V GetValue<V>()
        {
            return Parser.Parse<V>(this.Value);
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public ConfigProperty() { }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="key">Properties key.</param>
        /// <param name="value">Properties value.</param>
        public ConfigProperty(string key, object value)
        {
            this.Key = key;
            this.Value = value;
        }

        #region ========== IXmlSerializable ==========

        public System.Xml.Schema.XmlSchema GetSchema() { return null; }

        /// <summary>
        /// Custom implementation of ReadXML.
        /// </summary>
        /// <param name="reader"></param>
        public void ReadXml(System.Xml.XmlReader reader)
        {
            Type elementType = Type.GetType(reader.LocalName);
            Type thisType = typeof(ConfigProperty);

            if ((elementType.IsSubclassOf(thisType) || object.Equals(elementType, thisType)) && reader.MoveToContent() == XmlNodeType.Element)
            {
                this.Key = reader.GetAttribute("Key");
                this.Value = reader.GetAttribute("Value");
            }
        }


        /// <summary>
        /// Custom implementation of WriteXML.
        /// </summary>
        /// <param name="writer"></param>
        public void WriteXml(System.Xml.XmlWriter writer)
        {
            writer.WriteStartElement(this.GetType().ToString());
            writer.WriteAttributeString("Key", Key);
            writer.WriteAttributeString("Value", Value.ToString());
            writer.WriteEndElement();
        }

        #endregion
    }
}
